package com.ydc.ln.tutorial.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 获取局域网内IP
 * 参考：http://bbs.csdn.net/topics/270077403
 * 
 * @author ydc
 * @date 上午12:33:54 2013-5-28
 */
public class ScanIp01Test {
    public static void main(String[] args) {
        GoodWindowsExec.test("arp -a");
    }
}


class StreamGobbler extends Thread {
    InputStream is;
    String type;

    StreamGobbler(InputStream is, String type) {
        this.is = is;
        this.type = type;
    }

    public void run() {
        try {
            InputStreamReader isr = new InputStreamReader(is, "gbk");
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null)
                System.out.println(type + ">" + line);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}


class GoodWindowsExec {
    public static void test(String cmdLine) {
        try {
            String osName = System.getProperty("os.name");
            System.out.println("osName: " + osName);
            String[] cmd = new String[3];
            cmd[0] = "cmd.exe";
            cmd[1] = "/C";
            cmd[2] = cmdLine;
            Runtime rt = Runtime.getRuntime();
            System.out.println("Execing " + cmd[0] + " " + cmd[1] + " "
                    + cmd[2]);
            Process proc = rt.exec(cmd);

            System.out.println("------------------------------");
            // any error message?
            StreamGobbler errorGobbler =
                    new StreamGobbler(proc.getErrorStream(), "ERROR");

            // any output?
            StreamGobbler outputGobbler =
                    new StreamGobbler(proc.getInputStream(), "OUTPUT");

            // kick them off
            errorGobbler.start();
            outputGobbler.start();
            // any error???
            int exitVal = proc.waitFor();
            System.out.println("------------------------------");
            System.out.println("ExitValue: " + exitVal);
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}
